package com.wzdigit.wms.wms.service.transfer;

import com.wzdigit.mes.basic.api.BasicSimpleCodeRuleApi;
import com.wzdigit.wms.basic.client.response.Result;
import com.wzdigit.wms.basic.domain.inventory.GoodsPkg;
import com.wzdigit.wms.basic.enums.BooleanEnum;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.wms.service.core.GoodsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 在库模块-堆板服务类
 * Created by zyf on 2021/5/11 8:04
 */
@Slf4j
@Service
public class HeapAndMergerService {

    final String palletNoRuleCode = "virtualPalletCode";

    @Reference(version = "${dubbo.consumers.basic.simple.code.rule.api:1.0.0}", check = false)
    private BasicSimpleCodeRuleApi basicSimpleCodeRuleApi;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsMapper goodsMapper;

    /**
     * 堆板
     *
     * @param goodsSns
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public Result<Integer> heapAndMerger(List<String> goodsSns,String  userName){
        //生成虚拟卡板
        GoodsPkg goodsPkg = this.setGoodsPkg(userName);
        this.goodsService.getGoodsPkgMapper().insert(goodsPkg);
        goodsPkg.setUrl(String.format("%s_0", goodsPkg.getGoodsPkgId()));
        this.goodsService.getGoodsPkgMapper().updateUrlByGoodsPkgId(goodsPkg.getGoodsPkgId(), goodsPkg.getUrl());

        //堆板，即更新所传条码的外包装ID
        goodsMapper.updatePkgIdBySnList(goodsSns,goodsPkg.getGoodsPkgId(),userName);

        return new Result<>(true,"堆板成功",goodsPkg.getPkgSn());

    }

    private GoodsPkg setGoodsPkg(String userName) {
        GoodsPkg goodsPkg = new GoodsPkg();
        goodsPkg.setPkgSn(this.basicSimpleCodeRuleApi.GenerateCode(this.palletNoRuleCode));
        goodsPkg.setPkgLevel(1);
        goodsPkg.setPkgCategory("PALLET");
        goodsPkg.setPkgType(10);
        goodsPkg.setFatherPkgId(0);
        goodsPkg.setIsLeaf(BooleanEnum.TRUE.getCode());
        goodsPkg.setUrl(String.format("%s_0", goodsPkg.getGoodsPkgId()));
        goodsPkg.setCreateTime(new Date());
        goodsPkg.setModifyTime(new Date());
        goodsPkg.setCreateUser(userName);
        goodsPkg.setModifyUser(userName);
        return goodsPkg;
    }
}
